import { showMessage } from '@/components/antd-comp/message'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import { ButtonNumber } from '@/components/bs-ui/button'
import { DoubleRightOutlined } from '@ant-design/icons'
import { Button, Checkbox, Empty, Form, Input, Modal } from 'antd'
import { throttle } from 'lodash'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import '../../CallWordPage/css/styles.css'
import '../css/styles.css'

const CreateApplication = ({ open, setOpen, obj, submitData }) => {
  /* 取消 */
  const handleCancel = (e: React.MouseEvent<HTMLElement>) => {
    setOpen(false)
  }
  const [person, setPerson] = useState({
    name: '',
    content: '',
    contentNew: '',
    id: '',
    optimizeBtnHid: false
  })
  const { TextArea } = Input

  const { t } = useTranslation()
  /* 迭代轮次=输入 */
  const [iteration_rounds, setIterationRounds] = useState(1)

  useEffect(() => {
    setPerson({
      ...person,
      ...obj
    })
  }, [])

  /* 提示词优化选项 */
  const checkedList = [
    {
      value: '1',
      label: t('call.callCheckSeleQuality'),
      checked: false
    },
    {
      value: '2',
      label: t('call.callCheckSeleShorten'),
      checked: false
    },
    {
      value: '3',
      label: t('call.callCheckSeleThinking'),
      checked: false
    }
  ]
  const [checked, setCheckedList] = useState(checkedList)

  /* 显示按钮状态 */
  const btnStatus = {
    loading: false
  }
  const [btnStatusType, setBtnStatusType] = useState(btnStatus)

  // 优化
  const optimizeFun = e => {
    e.preventDefault()
    formState
      .validateFields()
      .then(values => {
        setBtnStatusType({
          loading: true
        })
        handleOptimizeReq(person.content, checked.join(), Number(iteration_rounds))
      })
      .catch(err => {
        console.log('err', err)
      })
  }
  // 提示词优化
  const areaRef = useRef(null)
  const esLinkSuccess = useRef(false)
  const updateOptimizeInfo = throttle(list => {
    setPerson({
      ...person,
      contentNew: list.join('')
    })
    if (areaRef.current?.scrollHeight) {
      // 自动滚动
      areaRef.current.scrollTop = areaRef.current.scrollHeight
    }
  }, 100)
  const handleOptimizeReq = async (prompt, types, iteration_rounds) => {
    esLinkSuccess.current = false
    try {
      const apiUrl = `/api/v1/prompt_plt/optimize?prompt=${encodeURIComponent(
        prompt
      )}&types=${types}&iteration_rounds=${iteration_rounds}`
      const eventSource = new EventSource(apiUrl)
      const msgList = []
      eventSource.onmessage = event => {
        if (!event.data) {
          setBtnStatusType({
            loading: false
          })
          return
        }

        esLinkSuccess.current = true
        const parsedData = JSON.parse(event.data)
        if (parsedData?.status && parsedData.status == 30) {
          updateOptimizeInfo(
            parsedData?.choices[0]?.delta?.content
              ? [parsedData.choices[0].delta.content]
              : [
                  '大模型advice:作为一名AI语言模型，我不能回答涉及色情、暴力、政治等敏感话题的问题。如果您有其他相关问题，请重新提问。'
                ]
          )
          return
        }
        switch (parsedData.type) {
          case 'prompt':
            msgList.push(parsedData.message)
            updateOptimizeInfo(msgList)
            break
          case 'end':
            setBtnStatusType({
              loading: false
            })
            if (parsedData.message) {
              showMessage({
                content: parsedData.message,
                type: 'error'
              })
            }
            break
        }
      }

      eventSource.onerror = (error: any) => {
        eventSource.close()
        if (error.data || !esLinkSuccess.current) {
          let msg = '优化失败'
          if (error.data) {
            msg = JSON.parse(error.data)
          }
          showMessage({
            content: msg,
            type: 'error'
          })
        }
        setBtnStatusType({
          loading: false
        })
      }
    } catch (error) {
      setBtnStatusType({
        loading: false
      })
    }
  }

  /* 更新checkList dialog的提示词优化选项 */
  function checkedSele(values) {
    setCheckedList(values)
  }

  /* 提交表单 */
  const submitOptimize = () => {
    if (!btnStatusType.loading) {
      submitData(person.contentNew || person.content)
    }
    setOpen(false)
  }

  const initFormData = {
    prompt: obj.content,
    types: [],
    iteration_rounds: 1
  }
  const [formState] = Form.useForm()

  return (
    <>
      <Modal
        width={825}
        className="modal_antcomp_case max-h-[40%]"
        title={t('call.callOptimize')}
        open={open}
        style={{ top: '10%' }}
        onCancel={handleCancel}
        maskClosable={false}
        footer={[
          <Button className="closeBtnStyles closeBtnWid" shape="round" onClick={() => setOpen(false)}>
            {t('cancel')}
          </Button>,

          <ThemeBtn className="closeBtnWid" onClick={submitOptimize}>
            {t('confirmButton')}
          </ThemeBtn>
        ]}
      >
        <div className="caseOverFlowY flex h-[100%] max-h-[500px] flex-col gap-4 py-2 pr-1 sm:max-w-[825px]">
          <Form
            name="normal_login"
            className="login-form bg-[#ffffff]"
            layout="vertical"
            form={formState}
            initialValues={initFormData}
          >
            {/* 优化 */}
            <div className="">
              <div className="flexRowStart application_edit_page_formCase">
                <Form.Item
                  name="types"
                  className="call-dialog-checkbox_name"
                  style={{ marginBottom: '0 !important' }}
                  rules={[{ required: true, message: t('call.callTemOption') }]}
                >
                  <div className="flexRowStart">
                    <Checkbox.Group
                      options={checkedList}
                      onChange={checkedValue => {
                        checkedSele(checkedValue)
                      }}
                      style={{ marginBottom: '0 !important' }}
                      className="call-dialog-checkbox_name call-dialog-checkbox ml-[4px]"
                    />
                    <div className="flexRowStart" style={{ marginLeft: '8px' }}>
                      <div className="call-dialog-checkbox_name">{t('call.callIteration')}</div>
                      <div className="roundsBox_put" style={{ marginLeft: '4px' }}>
                        <Form.Item
                          name="iteration_rounds"
                          rules={[{ required: true, message: t('call.callIteration') }]}
                        >
                          <ButtonNumber
                            value={iteration_rounds}
                            onChange={val => setIterationRounds(val)}
                            max={5}
                            min={1}
                            step={1}
                            className="h-[28px]"
                          />
                        </Form.Item>
                      </div>
                    </div>
                  </div>
                </Form.Item>
              </div>
              <div className="flexRow flexRowJustBet h-[400px]" style={{ marginTop: '16px' }}>
                <Form.Item
                  name="prompt"
                  rules={[
                    { required: true, message: t('call.callTemContIsNull') },
                    { max: 1024, message: t('call.callTemContJudgment') }
                  ]}
                  className="h-[368px]  w-[48%]"
                >
                  <div className="optionDiaOptimizeBox application_prompt_optimize_textarea relative h-[368px]">
                    <TextArea
                      value={person.content}
                      maxLength={1024}
                      onChange={e => setPerson({ ...person, content: e.target.value })}
                      placeholder={t('call.callTemCont')}
                      className="moduleContName h-[324px] border-none"
                      style={{ color: '#000000', resize: 'none' }}
                    />
                    <div className="text-gray-400" style={{ position: 'absolute', left: '12px', bottom: '12px' }}>
                      {`${person.content?.length || 0}/1024`}
                    </div>
                    <Button
                      loading={!!btnStatusType.loading}
                      type="primary"
                      size="small"
                      className="application_edit_btn"
                      style={{ background: '#5964F3' }}
                      onClick={optimizeFun}
                    >
                      {t('call.callOptimizeBtn')}
                    </Button>
                  </div>
                </Form.Item>
                <DoubleRightOutlined />
                <div className="mb-[24px] h-[368px] w-[48%] ">
                  {!person.contentNew && !btnStatusType.loading ? (
                    <Empty
                      className="flexColCen option-dia-prompt-empty m-[0] h-[368px] rounded-[6px] bg-[#F5F7FB]"
                      description={t('application.appliCallSettingPreview')}
                      image={
                        <svg xmlns="http://www.w3.org/2000/svg" width="49" height="48" viewBox="0 0 49 48" fill="none">
                          <path
                            d="M46.5 13V6C46.5 3.79086 44.7091 2 42.5 2H35.5M13.5 2H6.5C4.29086 2 2.5 3.79086 2.5 6V13M2.5 35V42C2.5 44.2091 4.29086 46 6.5 46H13.5"
                            stroke="#BBC6D8"
                            strokeWidth="2"
                          />
                          <circle cx="24.5" cy="24" r="14" stroke="black" strokeWidth="2" />
                          <path d="M42.5 42L34.5 34" stroke="black" strokeWidth="2" />
                          <path d="M19.5 19H29.5" stroke="#BBC6D8" strokeWidth="2" />
                          <path d="M19.5 29H29.5" stroke="#BBC6D8" strokeWidth="2" />
                          <path d="M16.5 24H32.5" stroke="#BBC6D8" strokeWidth="2" />
                        </svg>
                      }
                    />
                  ) : (
                    <TextArea
                      ref={areaRef}
                      // rows={20}
                      value={person.contentNew}
                      maxLength={500}
                      onChange={e => setPerson({ ...person, contentNew: e.target.value })}
                      placeholder={t('call.callTemCont')}
                      className="moduleContName option-dia-prompt-new h-[368px] bg-[#F5F7FB]"
                      style={{
                        color: '#5A6880',
                        background: '#F5F7FB',
                        padding: '12px 12px 10px',
                        boxSizing: 'border-box'
                      }}
                    />
                  )}
                </div>
              </div>
            </div>
          </Form>
        </div>
      </Modal>
    </>
  )
}

export default CreateApplication
